package com.swj.auth.controller;

import com.swj.common.core.model.SysUser;
import com.swj.common.core.model.vo.LogInVo;
import com.swj.common.core.model.vo.LoginUserVo;
import com.swj.auth.service.ISysLoginService;
import com.swj.common.core.utils.JwtUtils;
import com.swj.common.core.utils.ResponseUtil;
import com.swj.common.core.model.web.RestResult;
import com.swj.common.core.utils.SysStringUtil;
import com.swj.common.security.auth.AuthUtil;
import com.swj.common.security.service.TokenService;
import com.swj.common.security.utils.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 用户登录
 * @author 10834
 * @CreateTime 2019/6/17 15:21
 */
@RestController
public class UserTokenController {

    @Autowired
    private ISysLoginService sysLoginService;

    @Autowired
    private TokenService tokenService;

    /**
     * 登录
     *
     * @author swj
     * @CreateTime 2019/6/20 9:21
     */
    @PostMapping("/login")
    public RestResult<?> login(@RequestBody LogInVo logInVo) {
        //进行身份验证
        LoginUserVo loginUser = sysLoginService.logIn(logInVo);
        // 获取登录token
        return ResponseUtil.successWithObj(tokenService.createToken(loginUser));
    }

    @DeleteMapping("/logout")
    public RestResult<?> logout(HttpServletRequest request) {
        String token = SecurityUtil.getToken(request);
        if (SysStringUtil.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return ResponseUtil.success("退出登录成功");
    }

    @PostMapping("register")
    @Validated
    public RestResult<?> register(@RequestBody SysUser sysUser) {
        // 用户注册
        sysLoginService.register(sysUser);
        return ResponseUtil.successPosts("注册成功");
    }

}